<template>
  <el-card>
    <template #header>
      <div class="card-header">员工数据分析</div>
    </template>
    
    <div class="chart-container">
      <div ref="departmentChart" style="width: 100%; height: 400px;"></div>
    </div>
    
    <div class="chart-container" style="margin-top: 20px;">
      <div ref="positionChart" style="width: 100%; height: 400px;"></div>
    </div>
  </el-card>
</template>

<script setup>
import { onMounted, ref, nextTick } from 'vue'
import * as echarts from 'echarts'
import request from '@/utils/request'

const departmentChart = ref(null)
const positionChart = ref(null)

onMounted(async () => {
  await nextTick()
  initCharts()
  fetchChartData()
})

const initCharts = () => {
  // 部门分布图表
  const deptChart = echarts.init(departmentChart.value)
  deptChart.setOption({
    title: {
      text: '部门员工分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '部门',
        type: 'pie',
        radius: '50%',
        data: []
      }
    ]
  })
  
  // 职位分布图表
  const posChart = echarts.init(positionChart.value)
  posChart.setOption({
    title: {
      text: '职位分布',
      left: 'center'
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '人数',
        type: 'bar',
        data: []
      }
    ]
  })
}

const getStatisticsFromUsers = (users) => {
  // 部门统计
  const deptMap = {}
  const posMap = {}
  users.forEach(u => {
    deptMap[u.department] = (deptMap[u.department] || 0) + 1
    posMap[u.position] = (posMap[u.position] || 0) + 1
  })
  return {
    departments: Object.entries(deptMap).map(([name, value]) => ({ name, value })),
    positions: {
      labels: Object.keys(posMap),
      values: Object.values(posMap)
    }
  }
}
const fetchChartData = async () => {
  try {
    const users = await request.get('/users')
    const stats = getStatisticsFromUsers(users)
    const deptChart = echarts.getInstanceByDom(departmentChart.value)
    deptChart.setOption({
      series: [
        {
          data: stats.departments
        }
      ]
    })
    const posChart = echarts.getInstanceByDom(positionChart.value)
    posChart.setOption({
      xAxis: {
        data: stats.positions.labels
      },
      series: [
        {
          data: stats.positions.values
        }
      ]
    })
  } catch (error) {
    console.error('获取图表数据失败', error)
  }
}
</script>

<style scoped>
.chart-container {
  width: 100%;
}
</style>  